package com.xiaoxu.privatechat.util;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * @author xiaoxu
 * @description 项目通用工具类
 * @date 2023/2/13
 */
public class StringUtil {


    /**
     * 返回指定格式的日期字符串
     *
     * @param date      日期
     * @param formatter 模板
     * @return String
     */
    public static String getFormatterDate(Date date, String formatter) {
        SimpleDateFormat sdf = new SimpleDateFormat(formatter);
        return sdf.format(date);
    }

    /**
     * @param request 请求
     * @return boolean
     * @description 判断请求是否是ajax
     */
    public static boolean isAjax(HttpServletRequest request) {
        String header = request.getHeader("X-Requested-With");
        return "XMLHttpRequest".equals(header);
    }

    /**
     * @param inputStream 输入流
     * @return String
     * @description 从流读取字符串
     */
    public static String getStringFromInputStream(InputStream inputStream) {
        StringBuilder string = new StringBuilder();
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "GB2312"));
            String buf;
            try {
                while ((buf = bufferedReader.readLine()) != null) {
                    string.append(buf);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return string.toString();
    }

    /**
     * @param file 文件
     * @return String
     * @description 读取文件为String
     */
    public static String readFileToString(File file) {
        StringBuilder string = new StringBuilder();
        if (file != null) {
            try {
                BufferedReader br = new BufferedReader(new FileReader(file));
                String line;
                while ((line = br.readLine()) != null) {
                    string.append(line);
                }
                br.close();
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
        return string.toString();
    }

    /**
     * @param file 文件
     * @description 提交文件
     */
    public static void handleFile(File file) {
        if (file.isDirectory()) {
            File[] listFiles = file.listFiles();
            for (File f : Objects.requireNonNull(listFiles)) {
                handleFile(f);
            }
        } else {
            boolean Bool = file.delete();
            System.out.println(file.getName());
        }
    }


}
